package org.baitu.zzim.handler;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.baitu.zzim.model.ChatMessage;
import org.baitu.zzim.pojo.chat.ChatMessageOuterClass;
import org.baitu.zzim.service.ChannelManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static org.baitu.zzim.handler.JwtHandshakeAuthHandler.USER_ID_ATTR;

@Component
@Sharable
public class WebSocketProtoHandler extends SimpleChannelInboundHandler<ChatMessageOuterClass.ChatMessage> {

    @Autowired
    private ChannelManager channelManager;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接断开时
        channelManager.removeChannel(ctx.channel().attr(USER_ID_ATTR).get(), ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatMessageOuterClass.ChatMessage frame) throws Exception {
        // 这里可以添加消息解析逻辑
        channelManager.sendToUser(frame.getReceiver(),frame);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}